<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.operationCode" clearable placeholder="工序编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.operationName" clearable placeholder="工序名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select
          v-model="query.operationType"
          clearable
          filterable
          placeholder="工序类型"
          style="width: 185px;"
          class="filter-item"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.operation_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="620px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-tabs tab-position="left" v-model="productActiveName" style="height: 400px;">
            <el-tab-pane label="基础数据" name="basics">
              <el-form-item label="工序编号" prop="operationCode">
                <el-input v-model="form.operationCode" style="width: 370px;" />
              </el-form-item>
              <el-form-item label="工序名称" prop="operationName">
                <el-input v-model="form.operationName" style="width: 370px;" />
              </el-form-item>
              <el-form-item label="工序类型" prop="operationType">
                <el-select v-model="form.operationType" style="width: 370px" filterable placeholder="请选择">
                  <el-option
                    v-for="item in dict.operation_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="form.remark" :rows="3" type="textarea" style="width: 370px;" />
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="应用产品" name="product">
              <div class="treeDiv">
                <el-tree
                  :data="productData"
                  show-checkbox
                  node-key="code"
                  default-expand-all
                  ref="productTree"
                  highlight-current
                  :props="defaultProps">
                </el-tree>
              </div>
            </el-tab-pane>
            <el-tab-pane label="关联设备" name="device">
              <div class="treeDiv">
                <el-tree
                  :data="deviceData"
                  show-checkbox
                  node-key="code"
                  default-expand-all
                  ref="deviceTree"
                  highlight-current
                  :props="defaultProps">
                </el-tree>
              </div>
            </el-tab-pane>
          </el-tabs>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="operationCode" label="工序编号" width="150px" align="center"/>
        <el-table-column prop="operationName" label="工序名称" width="150px" align="center"/>
        <el-table-column prop="operationType" label="工序类型" width="150px" align="center">
          <template slot-scope="scope">
            {{ dict.label.operation_type[scope.row.operationType] }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" width="100px" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="150px" align="center"/>
        <el-table-column prop="updateBy" label="更新人" width="100px" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="150px" align="center"/>
        <el-table-column prop="remark" label="描述" width="250px" align="center"/>
        <el-table-column v-if="checkPer(['admin','craftOperation:edit','craftOperation:del'])" fixed="right" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
  import crudCraftOperation from '@/api/craft/craftOperation'
  import crudCraftOperationProduct from '@/api/craft/craftOperationProduct'
  import crudCraftOperationDevice from '@/api/craft/craftOperationDevice'
  import crudProductModel from '@/api/product/productModel'
  import crudFactoryModel from '@/api/factory/factoryModel'
  import CRUD, { presenter, header, form, crud } from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'

  const defaultForm = { id: null, operationCode: null, operationName: null, operationType: null, remark: null, createBy: null, createTime: null, updateBy: null, updateTime: null }
  export default {
    name: 'CraftOperation',
    components: { pagination, crudOperation, rrOperation, udOperation },
    mixins: [presenter(), header(), form(defaultForm), crud()],
    dicts: ['operation_type'],
    cruds() {
      return CRUD({
        title: '工序',
        url: 'api/craftOperation',
        idField: 'id',
        sort: 'id,desc',
        optShow: {
          add: true,
          edit: true,
          del: true,
          download: false,
          reset: true,
          import: true
        },
        crudMethod: { ...crudCraftOperation }})
    },
    data() {
      return {
        productData: [],
        productActiveName: 'basics',
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        deviceData: [],
        permission: {
          add: ['admin', 'craftOperation:add'],
          edit: ['admin', 'craftOperation:edit'],
          del: ['admin', 'craftOperation:del']
        },
        rules: {
          operationCode: [
            { required: true, message: '工序编号不能为空', trigger: 'blur' }
          ],
          operationName: [
            { required: true, message: '工序名称不能为空', trigger: 'blur' }
          ],
          operationType: [
            { required: true, message: '工序类型不能为空', trigger: 'blur' }
          ]
        },
        queryTypeOptions: [
          { key: 'id', display_name: 'ID' },
          { key: 'operationCode', display_name: '工序编号' },
          { key: 'operationName', display_name: '工序名称' },
          { key: 'operationType', display_name: '工序类型' },
          { key: 'remark', display_name: '描述' },
          { key: 'createBy', display_name: '创建人' },
          { key: 'updateBy', display_name: '更新人' }
        ]
      }
    },
    methods: {
      // 钩子：在获取表格数据之前执行，false 则代表不获取数据
      [CRUD.HOOK.beforeRefresh]() {
        return true
      },
      //新增/修改之前
      [CRUD.HOOK.beforeToCU](crud) {
        //初始产品树
        this.initProductTree();
        //初始化设备树
        this.initDeviceTree();
        return true
      },
      //新增之前
      [CRUD.HOOK.afterToAdd](crud,param) {
        //清空树
        this.$refs.productTree.setCheckedKeys([]);

        //清空树
        this.$refs.deviceTree.setCheckedKeys([]);
        return true
      },
      //编辑之前
      [CRUD.HOOK.afterToEdit](crud,param) {
        //加载设置产品数据
        this.setProductTreeValue(param);

        //加载设置设备数据
        this.setDeviceTreeValue(param);
        return true
      },
      //表单提交之前
      [CRUD.HOOK.beforeSubmit](crud) {
        //获取选中的产品值
        const keys = this.getProductTreeValue();

        //获取选中的设备值
        const deviceKeys = this.getDeviceTreeValue();


        if(!keys || keys.length == 0){
          this.productActiveName = 'product';
          this.$notify.error({
            title: '错误',
            message: '请选择产品型号后再提交！'
          });
          return false;
        }

        if(!deviceKeys || deviceKeys.length == 0){
          this.productActiveName = 'device';
          this.$notify.error({
            title: '错误',
            message: '请选择关联的设备后再提交！'
          });
          return false;
        }



        const products = [];
        for (const key of keys) {
          products.push({operationCode: crud.form.operationCode ,productCode:key});
        }

        const devices = [];
        for (const key of deviceKeys) {
          devices.push({operationCode: crud.form.operationCode ,deviceCode:key});
        }
        crud.form.products = products;
        crud.form.devices = devices;

        return true;
      },
      //初始产品树
      initProductTree(){
        crudProductModel.getTree().then(res =>{
          this.productData = res;
        });
      },
      //初始化设备树
      initDeviceTree(){
        crudFactoryModel.getTree().then(res =>{
          this.deviceData = res;
        })
      },

      //设置产品选中
      setProductTreeValue(param){
        crudCraftOperationProduct.list({operationCode : param.operationCode}).then(res =>{
          const keys = [];
          if(res){
            for (const index in res) {
              keys.push(res[index].productCode);
            }
          }
          this.$refs.productTree.setCheckedKeys(keys);
        })
      },
      setDeviceTreeValue(param){
        crudCraftOperationDevice.list({operationCode : param.operationCode}).then(res =>{
          const keys = [];
          if(res){
            for (const index in res) {
              keys.push(res[index].deviceCode);
            }
          }
          this.$refs.deviceTree.setCheckedKeys(keys);
        })
      },
      //获取选中的产品
      getProductTreeValue(){
        const nodes = this.$refs.productTree.getCheckedNodes();
        const keys = [];
        if(!nodes || nodes.length == 0){
          return keys;
        }
        for (const index in nodes) {
          if(nodes[index].type == 'model'){
            keys.push(nodes[index].code);
          }
        }
        return keys;
      },
      //获取选中的设备
      getDeviceTreeValue(){
        const nodes = this.$refs.deviceTree.getCheckedNodes();
        const keys = [];
        if(!nodes || nodes.length == 0){
          return keys;
        }
        for (const index in nodes) {
          if(nodes[index].type == '5'){
            keys.push(nodes[index].code);
          }
        }
        return keys;
      }

    }
  }
</script>

<style scoped>
  .treeDiv {
    height: 380px;
    overflow-x: hidden;
    overflow-y: scroll;
  }
</style>
